// 智能客服交互脚本 - Python后端版本

// DOM元素获取
const chatIcon = document.getElementById('chat-icon');
const chatContainer = document.getElementById('chat-container');
const closeBtn = document.getElementById('close-btn');
const minimizeBtn = document.getElementById('minimize-btn');
const userInput = document.getElementById('user-input');
const sendBtn = document.getElementById('send-btn');
const chatMessages = document.getElementById('chat-messages');
const modelSelectBtn = document.getElementById('model-select-btn');
const modelDropdown = document.getElementById('model-dropdown');
const knowledgeToggleBtn = document.getElementById('knowledge-toggle-btn');
const knowledgeStatusIcon = document.getElementById('knowledge-status-icon');

// 生成唯一会话ID
const sessionId = 'session_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);

// 模型选择配置
let useOllama = false; // 默认不使用Ollama
let useMock = true; // 默认使用模拟回复
let useKnowledge = true; // 默认使用知识库功能

// 打开聊天窗口
function openChat() {
    chatContainer.classList.remove('slide-out');
    chatContainer.classList.add('slide-in');
    chatContainer.style.transform = 'translateX(0)';
    setTimeout(() => {
        userInput.focus();
    }, 300);
}

// 关闭聊天窗口
function closeChat() {
    chatContainer.classList.remove('slide-in');
    chatContainer.classList.add('slide-out');
    setTimeout(() => {
        chatContainer.style.transform = 'translateX(100%)';
    }, 280);
}

// 最小化聊天窗口（简单实现，实际项目中可以扩展）
function minimizeChat() {
    closeChat();
}

// 添加消息到聊天窗口
function addMessage(text, isUser = false, allowHtml = false) {
    const messageDiv = document.createElement('div');
    messageDiv.classList.add('flex', 'items-start', 'mb-4', 'message-enter');
    
    if (isUser) {
        messageDiv.classList.add('justify-end');
        messageDiv.innerHTML = `
            <div class="bg-primary text-white p-3 rounded-lg max-w-[80%] chat-bubble-user shadow-sm">
                <p>${text}</p>
            </div>
            <div class="w-8 h-8 rounded-full bg-gray-300 flex items-center justify-center text-gray-600 ml-2 flex-shrink-0">
                <i class="fa fa-user"></i>
            </div>
        `;
    } else {
        messageDiv.innerHTML = `
            <div class="w-8 h-8 rounded-full bg-primary flex items-center justify-center text-white mr-2 flex-shrink-0">
                <i class="fa fa-robot"></i>
            </div>
            <div class="bg-white p-3 rounded-lg max-w-[80%] chat-bubble-bot shadow-sm">
                ${allowHtml ? text : `<p>${text}</p>`}
            </div>
        `;
    }
    
    chatMessages.appendChild(messageDiv);
    chatMessages.scrollTop = chatMessages.scrollHeight;
}

// 显示"正在输入"提示
function showTypingIndicator() {
    const typingDiv = document.createElement('div');
    typingDiv.id = 'typing-indicator';
    typingDiv.classList.add('flex', 'items-start', 'mb-4');
    typingDiv.innerHTML = `
        <div class="w-8 h-8 rounded-full bg-primary flex items-center justify-center text-white mr-2 flex-shrink-0">
            <i class="fa fa-robot"></i>
        </div>
        <div class="bg-white p-3 rounded-lg chat-bubble-bot shadow-sm">
            <div class="typing-indicator">
                <span></span>
                <span></span>
                <span></span>
            </div>
        </div>
    `;
    
    chatMessages.appendChild(typingDiv);
    chatMessages.scrollTop = chatMessages.scrollHeight;
}

// 移除"正在输入"提示
function removeTypingIndicator() {
    const typingDiv = document.getElementById('typing-indicator');
    if (typingDiv) {
        chatMessages.removeChild(typingDiv);
    }
}

// 调用Python后端API获取回复
async function callPythonBackend(userMessage) {
    try {
        // 向后端发送请求
        const response = await fetch('/api/chat', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                message: userMessage,
                session_id: sessionId,
                use_mock: useMock, // 使用全局配置
                use_ollama: useOllama, // 是否使用本地Ollama模型
                use_knowledge: useKnowledge // 是否使用知识库
            })
        });
        
        if (!response.ok) {
            throw new Error(`后端API调用失败: ${response.status}`);
        }
        
        const data = await response.json();
        return data;
        
    } catch (error) {
        console.error('后端API调用错误:', error);
        return { reply: '抱歉，我当前无法为您提供回答。请稍后再试或联系人工客服。', knowledge_used: false };
    }
}

// 发送消息处理函数
async function sendMessage() {
    const message = userInput.value.trim();
    if (message === '') return;
    
    // 添加用户消息
    addMessage(message, true);
    userInput.value = '';
    
    // 显示"正在输入"提示
    showTypingIndicator();
    
    try {
        // 调用Python后端获取回复
        const response = await callPythonBackend(message);
        
        // 移除"正在输入"提示并显示回复
        removeTypingIndicator();
        
        let replyContent = response.reply;
        
        // 如果使用了知识库，可以在回复中添加一个标记
        if (response.knowledge_used) {
            replyContent += '<span class="knowledge-source" style="font-size: 0.8em; color: #3B82F6; margin-left: 5px;"><i class="fa fa-book" title="该回答基于知识库内容"></i></span>';
        }
        
        addMessage(replyContent, false);
    } catch (error) {
        console.error('发送消息错误:', error);
        removeTypingIndicator();
        addMessage('抱歉，处理您的请求时出现错误。请稍后再试。', false);
    }
}

// 切换知识库功能
function toggleKnowledge() {
    useKnowledge = !useKnowledge;
    updateKnowledgeStatus();
}

// 更新知识库状态显示
function updateKnowledgeStatus() {
    if (knowledgeStatusIcon) {
        if (useKnowledge) {
            knowledgeStatusIcon.className = 'fa fa-book text-green-500';
            knowledgeStatusIcon.title = '知识库功能已启用';
        } else {
            knowledgeStatusIcon.className = 'fa fa-book text-gray-400';
            knowledgeStatusIcon.title = '知识库功能已禁用';
        }
    }
}

// 切换模型下拉菜单
function toggleModelDropdown() {
    if (modelDropdown) {
        modelDropdown.classList.toggle('hidden');
    }
}

// 设置模型
function setModel(modelType) {
    switch(modelType) {
        case 'mock':
            useMock = true;
            useOllama = false;
            break;
        case 'openai':
            useMock = false;
            useOllama = false;
            break;
        case 'ollama':
            useMock = false;
            useOllama = true;
            break;
    }
    
    // 更新按钮文本
    if (modelSelectBtn) {
        const modelNames = {
            'mock': '模拟回复',
            'openai': 'OpenAI API',
            'ollama': '本地Ollama'
        };
        modelSelectBtn.textContent = modelNames[modelType] || '模型';
    }
    
    // 隐藏下拉菜单
    if (modelDropdown) {
        modelDropdown.classList.add('hidden');
    }
}

// 绑定事件监听器
chatIcon.addEventListener('click', openChat);
closeBtn.addEventListener('click', closeChat);
minimizeBtn.addEventListener('click', minimizeChat);
sendBtn.addEventListener('click', sendMessage);
userInput.addEventListener('keypress', (e) => {
    if (e.key === 'Enter') {
        sendMessage();
    }
});

// 绑定模型选择和知识库切换事件
if (modelSelectBtn) {
    modelSelectBtn.addEventListener('click', toggleModelDropdown);
}

if (knowledgeToggleBtn) {
    knowledgeToggleBtn.addEventListener('click', toggleKnowledge);
}

// 添加模型切换按钮到聊天窗口
function addModelToggleControls() {
    const chatHeader = chatContainer.querySelector('.bg-primary');
    
    // 创建一个包含控制选项的下拉菜单
    const modelControls = document.createElement('div');
    modelControls.id = 'model-controls';
    modelControls.style.display = 'none';
    modelControls.className = 'absolute top-full right-0 mt-2 bg-white rounded-md shadow-lg p-2 w-48 z-50';
    modelControls.innerHTML = `
        <div class="text-sm text-gray-700 mb-2">模型选择：</div>
        <div class="flex items-center mb-2">
            <input type="radio" id="use-mock" name="model-type" checked>
            <label for="use-mock" class="ml-2 text-sm">模拟回复 (演示用)</label>
        </div>
        <div class="flex items-center mb-2">
            <input type="radio" id="use-openai" name="model-type">
            <label for="use-openai" class="ml-2 text-sm">OpenAI API</label>
        </div>
        <div class="flex items-center">
            <input type="radio" id="use-ollama" name="model-type">
            <label for="use-ollama" class="ml-2 text-sm">本地Ollama模型</label>
        </div>
    `;
    
    // 创建切换按钮
    const modelToggleBtn = document.createElement('button');
    modelToggleBtn.className = 'text-white px-2 py-1 rounded text-sm hover:bg-secondary transition-colors';
    modelToggleBtn.textContent = '模型';
    modelToggleBtn.onclick = (e) => {
        e.stopPropagation();
        modelControls.style.display = modelControls.style.display === 'none' ? 'block' : 'none';
    };
    
    // 点击其他地方关闭下拉菜单
    document.addEventListener('click', () => {
        modelControls.style.display = 'none';
    });
    
    // 阻止点击下拉菜单内部时关闭
    modelControls.addEventListener('click', (e) => {
        e.stopPropagation();
    });
    
    // 绑定模型选择事件
    document.getElementById('use-mock')?.addEventListener('change', () => {
        useMock = true;
        useOllama = false;
        console.log('已切换到模拟回复模式');
    });
    
    document.getElementById('use-openai')?.addEventListener('change', () => {
        useMock = false;
        useOllama = false;
        console.log('已切换到OpenAI API模式');
    });
    
    document.getElementById('use-ollama')?.addEventListener('change', () => {
        useMock = false;
        useOllama = true;
        console.log('已切换到本地Ollama模型模式');
    });
    
    // 添加到DOM
    chatHeader.appendChild(modelToggleBtn);
    chatHeader.appendChild(modelControls);
}

// 页面加载完成后，添加一些动画效果和初始化
window.addEventListener('load', () => {
    // 初始化客服图标样式
    chatIcon.style.opacity = '0';
    chatIcon.style.transition = 'opacity 0.5s ease-in-out';
    
    // 给客服图标添加出现动画
    setTimeout(() => {
        chatIcon.style.opacity = '1';
    }, 1000);
    
    // 初始化系统状态
    console.log('智能客服系统已初始化，会话ID:', sessionId);
    console.log('使用Python后端处理LLM请求');
    console.log('模型切换功能已启用，当前模式: 模拟回复');
    
    // 延迟添加模型切换控件，确保DOM已完全加载
    setTimeout(() => {
        addModelToggleControls();
    }, 500);
});

// 响应式调整
window.addEventListener('resize', () => {
    if (window.innerWidth <= 768) {
        // 小屏幕下的特殊处理
    }
});